package com.srv.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.zip.*;

public class ResponseTool {
	private static Log log = LogFactory.getLog(ResponseTool.class);
	private final static String disableGizp="disableGzip";
	private final static String acceptEncoding="Accept-Encoding";
	private final static String contentEncoding="Content-Encoding";
	private final static String str_false="false";
	private final static String str_gzip="gzip";
	/**
	  * 响应客户端请求(自动支持gzip压缩).	  
	  * @param request
	  * @param response
	  * @param result
	  * @throws ServletException
	  * @throws IOException
	  */
     public static void repsone(HttpServletRequest request,HttpServletResponse response,ResponseResult result)throws ServletException, IOException{
       PrintWriter out;
	   if(isGzipSupported(request)&& !isGzipDisabled(request))
	   {
		   out=getGzipWriter(response);
		   response.setHeader(contentEncoding,str_gzip);
		   log.debug("the client is gzip");
	   }
	   else
	   {
		   out=response.getWriter();
	   }    	 
	 	out.print(result.toJson());				
	 	out.flush();
	 	out.close();
     }
     private static boolean isGzipDisabled(HttpServletRequest request)
     {
      String flag=(String)request.getHeader(disableGizp);
      return ((flag!=null)&&(!flag.equalsIgnoreCase(str_false)));
     }
     private static boolean isGzipSupported(HttpServletRequest request)
     {
      String encoding=(String)request.getHeader(acceptEncoding);
      return ((encoding!=null)&&(encoding.indexOf(str_gzip)!= -1));
     }
     private static PrintWriter getGzipWriter(HttpServletResponse response)
     throws IOException
    {
     return new PrintWriter(new GZIPOutputStream(response.getOutputStream()));
    }
     
}
